package com.ers.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.ers.dao.UserDao;
import com.ers.model.User;

@Repository
public class UserDaoImpl implements UserDao{
	@Autowired
	private SessionFactory sessionFactory;	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public int save(User u ) {		
		Integer i = (Integer)sessionFactory.getCurrentSession().save(u);	
		return i;
	}

	@Override
	public List<User> searchByLoginName(String loginName,String password) {
		List<User> users = new ArrayList<User>();
		if(loginName == null || password == null || loginName.equals("") || password.equals("")){
			return users;
		}
		users = (List<User>)sessionFactory.getCurrentSession().createCriteria(User.class)
				.add(Restrictions.eq("loginName", loginName)).add(Restrictions.eq("password", password)).list();

		return users;
	}
	
	public User loadById(int id){
		return (User)sessionFactory.getCurrentSession().get(User.class, id);
	}
	@Override
	public boolean updateByInfo(User u) {
		String hql = "update User u set u.name=:name , u.password=:password,u.phone=:phone,u.mailbox=:mailbox where u.id=:id";
		sessionFactory.getCurrentSession().createQuery(hql).setString("name", u.getName()).setString("password", u.getPassword())
		.setString("phone", u.getPhone()).setString("mailbox", u.getMailbox()).setInteger("id", u.getId()).executeUpdate();
		return true;
	}
	@Override
	public void updatePwd(String mailbox) {
		sessionFactory.getCurrentSession().createQuery("update User u set u.password='1' where u.mailbox=:mailbox").setString("mailbox", mailbox).executeUpdate();
	}

}
